/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package coalescent.is;

import coalescent.Genealogy;
import coalescent.model.PopGenModel;
import coalescent.statistic.AC;
import commons.is.Factor;
import commons.is.Factor_Multi;
import commons.is.Proposal_w_Prob;

import java.math.BigDecimal;
import java.util.List;

import static commons.core.Singletons.MATHCONTEXT_128_HALF_UP;

/**
 * @since
 * @version
 * @author Susanta Tewari
 * @history Created on 4/4/13.
 */
public class GFactors {

    private GFactors() {}

    /**
     * @param proposal
     * @param <S>
     * @param <M>
     * @return
     */
    public static <S extends AC<S, M>, M extends PopGenModel> Factor<Genealogy<S,
                   M>> of(final Proposal_w_Prob<Genealogy<S, M>> proposal) {

        return new Factor<Genealogy<S, M>>() {

            @Override
            public BigDecimal getValue(final Genealogy<S, M> x) {

                final BigDecimal targetVal     = x.probability();
                final BigDecimal proposalValue = proposal.probability(x);

                return targetVal.divide(proposalValue, MATHCONTEXT_128_HALF_UP);
            }
        };
    }

    public static <S extends AC<S, M>, M extends PopGenModel> Factor_Multi<Genealogy<S,
                   M>> of_Multi(final GProposal<S, M> proposal, final List<M> models) {

        return new Factor_Multi<Genealogy<S, M>>() {

            @Override
            public BigDecimal[] getValue(final Genealogy<S, M> x) {

                final BigDecimal[] result = new BigDecimal[models.size()];

                for (int i = 0; i < models.size(); i++) {

                    final M m = models.get(i);

                    x.setModel(m);

                    final BigDecimal t_val = x.probability();
                    final BigDecimal p_val = proposal.probability(x);

                    result[i] = t_val.divide(p_val, MATHCONTEXT_128_HALF_UP);
                }

                return result;
            }
            @Override
            public int size() {
                return models.size();
            }
        };
    }
}
